package com.amigo.online.provider.adv.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.amigo.online.common.param.common.KeyValueModel;
import com.amigo.online.provider.adv.common.ConstantValue;
import com.amigo.online.provider.adv.mapper.AdvTantanStockMapper;
import com.amigo.online.provider.adv.service.AdvTantanClickRecordService;
import com.amigo.online.provider.adv.service.AdvTantanLookRecordService;
import com.amigo.online.provider.adv.service.AdvTantanStockService;
import com.amigo.online.provider.adv.service.common.AbstractAdvStockService;

@Service
public class AdvTantanStockServiceImpl extends AbstractAdvStockService implements AdvTantanStockService {

    @Autowired
    AdvTantanStockMapper advTantanStockMapper;

    @Autowired
    AdvTantanLookRecordService advTantanLookRecordService;

    @Autowired
    AdvTantanClickRecordService advTantanClickRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class) //, propagation = Propagation.SUPPORTS
    public void storageAdvRestNumberFromRedis(List<KeyValueModel<Long, Integer>> updateObjectList) {
        advTantanStockMapper.storageAdvRestNumberFromRedis(updateObjectList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordLookTantanAdv(Long advId, String device, Long userId) {
        //扣减库存
        long result = stockService.stock(ConstantValue.ADV_TANTAN_STOCK, String.valueOf(advId), -1);
        if (result == 0) {
            //该广告库存已经消耗完,   是否需要清空list？
            //手动入库
            advTantanStockMapper.recordOverUsedNumber(advId);
        } else if (result == -1) {
            logger.error("该首页资源未被正确初始化: 资源的ID:" + advId);
        }

        advTantanLookRecordService.recordTantanAdvLooked(advId, device, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordClickTantanAdv(Long advId, String device, Long userId) {
        advTantanStockMapper.recordClickNumber(advId);
        advTantanClickRecordService.recordTantanAdvClicked(advId, device, userId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void deductionTantanAdvLookStock(Long advId) {
        //扣减库存
        long result = stockService.stock(ConstantValue.ADV_TANTAN_STOCK, String.valueOf(advId), -1);
        if (result == 0) {
            //该广告库存已经消耗完,   是否需要清空list？
            //手动入库
            advTantanStockMapper.recordOverUsedNumber(advId);
        } else if (result == -1) {
            logger.error("该首页资源未被正确初始化: 资源的ID:" + advId);
        }
    }

}
